<template>
    <view>
        <view>
            <form>
                <view class="cu-form-group margin-top">
                    <view class="title">标题</view>
                    <input @input="Input" data-field="title" placeholder="标题"/>
                </view>
                <view class="cu-form-group margin-top">
                    <view class="title" v-if="type === 'master'">是否悬赏</view>
                    <view class="title" v-if="type === 'thing'">是否需要报酬</view>
                    <radio-group @change="Input" data-field="hasReward">
                        <label>
                            <radio value="1" class="blue"/>
                            <text class="margin-left-xs">是</text>
                        </label>
                        <label>
                            <radio value="0" class="margin-left-l blue" checked/>
                            <text class="margin-left-xs">否</text>
                        </label>
                    </radio-group>
                </view>
                <view v-if="Detail.hasReward === '1'" class="cu-form-group">
                    <view class="title" v-if="type === 'master' && Detail.hasReward === '1'">悬赏内容</view>
                    <input @input="Input" data-field="reward" v-if="type === 'master' && Detail.hasReward === '1'"
                           placeholder="悬赏内容"/>
                    <view class="title" v-if="type === 'thing' && Detail.hasReward === '1'">报酬内容</view>
                    <input @input="Input" data-field="reward" v-if="type === 'thing' && Detail.hasReward === '1'"
                           placeholder="报酬内容"/>
                </view>
                <view class="cu-bar bg-white margin-top">
                    <view class="action">图片上传</view>
                    <view class="action">{{ imgList.length }}/9</view>
                </view>
                <view class="cu-form-group">
                    <view class="grid col-4 grid-square flex-sub">
                        <view class="bg-img" @tap="ViewImage" :data-url="imgList[index]"
                              v-for="(item, index) in imgList" :key="index">
                            <image :src="imgList[index]" mode="aspectFill"></image>

                            <view class="cu-tag bg-red" @tap.stop.prevent="DelImg" :data-index="index">
                                <text class="cuIcon-close"></text>
                            </view>
                        </view>
                        <view class="solids" @tap="ChooseImage" v-if="imgList.length < 9">
                            <text class="cuIcon-cameraadd"></text>
                        </view>
                    </view>
                </view>
                <view class="cu-form-group">
                    <view class="title">标签</view>
                    <input @input="Input" data-field="tag" placeholder="标签（多个用英文逗号,隔开）"/>
                </view>
                <view class="cu-form-group align-start">
                    <view class="title">描述</view>
                    <textarea maxlength="-1" @input="Input" data-field="content" placeholder="内容"></textarea>
                </view>
                <view class="flex justify-center">
                    <button
                        class="cu-btn bg-blue shadow-redr"
                        style="width: 80%;"
                        data-type="thing"
                        @tap="Submit">
                        发布
                    </button>
                </view>
            </form>

        </view>
    </view>
</template>

<script>
// pages/publish/publish.js
const app = getApp();

const getData = (url, param) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: url,
            method: 'POST',
            data: param,
            header: {
                'Content-Type': 'application/json'
            },

            success(res) {
                resolve(res.data);
            },

            fail(err) {
                reject(err);
            }
        });
    });
}; //获取随机数

const charts = [
    '0', '1', '2', '3', '4',
    '5', '6', '7', '8', '9',
    'A', 'B', 'C', 'D', 'E',
    'F', 'G', 'H', 'I', 'J',
    'K', 'L', 'M', 'N', 'O',
    'P', 'Q', 'R', 'S', 'T',
    'U', 'V', 'W', 'X', 'Y',
    'Z'
];

const random = function generateMixed(n) {
    var res = '';

    for (var i = 0; i < n; i++) {
        var id = Math.ceil(Math.random() * 35);
        res += charts[id];
    }

    return res;
};

export default {
    data() {
        return {
            type: '',
            //发布信息类型
            Detail: {
                hasReward: 0,

                //默认不需要悬赏
                type: '',

                SafeCode: '',
                code: ''
            },
            //信息详情
            webConfig: {
                open_comment: ''
            },
            index: '',
            imgList: [],
            code: '1'
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        uni.showLoading({
            title: '加载中...'
        });
        let that = this;
        that.SafeCode = uni.getStorageSync('SafeCode'); //获取网站配置

        uni.request({
            url: app.globalData.ApiUrl + 'api/Android/webConfig',
            //这里填写你的接口路径
            header: {
                'Content-Type': 'application/json'
            },
            success: function (res) {
                that.setData({
                    webConfig: res.data
                });
                uni.hideLoading();
            }
        }); //先确定页面类型

        that.setData({
            type: options.type,
            'Detail.type': options.type,
            'Detail.SafeCode': uni.getStorageSync('SafeCode')
        });

        let code = random(32);
        that.setData({
            code: code,
            'Detail.code': code
        });
    },
    onPullDownRefresh: function () {
        uni.stopPullDownRefresh();
    },
    methods: {
        Input: function (e) {


            let field = 'Detail.' + e.currentTarget.dataset.field;
            let val = e.detail.value;
            this.setData({
                [field]: val
            });
            // this.Detail.e.currentTarget.dataset.field = val;
            console.log(this.Detail);
        },

        ChooseImage: function (e) {
            let that = this;
            uni.chooseImage({
                count: 9,
                //默认9
                sizeType: ['original'],
                //可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album', 'camera'],
                //从相册选择
                success: (res) => {


                    if (that.imgList.length !== 0) {
                        that.setData({
                            imgList: that.imgList.concat(res.tempFilePaths)
                        });

                    } else {
                        that.setData({
                            imgList: res.tempFilePaths
                        });
                    }
                }
            });
        },

        ViewImage(e) {
            uni.previewImage({
                urls: this.imgList,
                current: e.currentTarget.dataset.url
            });
        },

        DelImg(e) {
            this.imgList.splice(e.currentTarget.dataset.index, 1);
            this.setData({
                imgList: this.imgList
            });
        },

        Submit: function (e) {
            let that = this;
            let msg;

            getData(app.globalData.ApiUrl + 'api/Android/SubmitItem', that.Detail).then(
                (res) => {

                    if (res.result !== 'success') {
                        console.log(res);

                        msg = res.msg;

                        uni.showToast({
                            title: msg,
                            icon: 'error',
                            duration: 1500
                        });

                    } else {
                        let allReady = true; //假设目前一切正常

                        //使用循环上传
                        for (let i = 0; i < that.imgList.length; i++) {
                            uni.uploadFile({
                                url: app.globalData.ApiUrl + 'api/Android/UploadApi',
                                filePath: that.imgList[i],
                                name: 'img_file',
                                formData: {
                                    code: that.code
                                },
                                success: function (res) {

                                    let result = JSON.parse(res.data);

                                    if (result.result === 'success') {
                                        console.log('上传成功' + i);
                                    } else {
                                        allReady = false;
                                        console.log('上传失败');
                                    }
                                },
                                fail: function (res) {
                                    allReady = false;
                                }
                            });
                        }

                        if (allReady) {
                            uni.showToast({
                                title: '发布成功！',
                                icon: 'success',
                                duration: 1500
                            });
                            setTimeout(function () {
                                uni.navigateBack();
                            }, 1500);
                        } else {
                            uni.showToast({
                                title: "部分图片上传失败",
                                icon: 'error',
                                duration: 1500
                            });
                        }


                    }
                }
            );


        }
    }
};
</script>
<style>
@import './publish.css';
</style>
